import { debug } from '../config'
import { getCookie } from '../utils/common'
import axios from 'axios'
import { errModal } from '../utils/globalModal'
import store from '../store'
import { logout } from '../store/user/actionCreators.js'

export default async (url, options = {}) => {
  // const prefix = 'http://127.0.0.1:7001/'
  const prefix = window.location.origin + '/' + (debug ? 'beta/' : 'v2/')
  const token = getCookie('token')
  options.headers = options.headers || {}
  if (token) options.headers.token = token

  console.log(prefix + url)
  try {
    const {
      data: { data, desc, code },
    } = await axios(prefix + url, options)
    if (code === '0') {
      return JSON.parse(data)
    } else if (code === '-2') {
      const history = store.getState()['pageState']['history']
      history.push('/login')
      // 登出
      store.dispatch(logout())
      errModal({
        title: '错误',
        content: desc,
      })
    } else {
      throw new Error(desc)
    }
  } catch (e) {
    console.error('api 请求错误', e)
    throw e
  }
}
